// 模型性能页面JavaScript

// 全局函数：打开模型体验模态框
function openModelDetail(modelType) {
    console.log('打开模型体验模态框:', modelType);
    
    // 创建并显示模态框
    if (window.ModelExperienceModal) {
        window.ModelExperienceModal.open(modelType);
    } else {
        console.log('模态框未初始化，请等待页面完全加载');
    }
}

const ModelsPerformance = {
    // 模型数据
    modelData: {
        "随机森林": {
            training_time: 0.898,
            mse: 0.006470,
            rmse: 0.080438,
            mae: 0.011437,
            r2: 0.991896
        },
        "XGBoost": {
            training_time: 1.408,
            mse: 0.007981,
            rmse: 0.089337,
            mae: 0.008972,
            r2: 0.990004
        },
        "LSTM": {
            training_time: 148.138,
            mse: 0.004328,
            rmse: 0.065784,
            mae: 0.012316,
            r2: 0.994590
        }
    },

    // 初始化状态
    isInitialized: false,
    chartInstances: {},

    // 初始化
    init: function() {
        // 检查模型性能页面是否可见
        const modelsSection = document.getElementById('models');
        if (!modelsSection || !modelsSection.classList.contains('active')) {
            console.log('模型性能页面不可见，跳过初始化');
            return;
        }

        this.setupTabSwitching();
        this.setupRefreshButton();
        
        // 延迟初始化图表，确保容器有正确尺寸
        setTimeout(() => {
            this.initCharts();
            this.isInitialized = true;
        }, 200);
        
        console.log('模型性能页面已初始化');
    },

    // 设置标签页切换
    setupTabSwitching: function() {
        const tabButtons = document.querySelectorAll('.tab-button');
        const tabPanels = document.querySelectorAll('.tab-panel');

        tabButtons.forEach(button => {
            button.addEventListener('click', () => {
                const targetTab = button.getAttribute('data-tab');

                // 移除所有活动状态
                tabButtons.forEach(btn => btn.classList.remove('active'));
                tabPanels.forEach(panel => panel.classList.remove('active'));

                // 激活当前标签
                button.classList.add('active');
                const targetPanel = document.querySelector(`[data-content="${targetTab}"]`);
                if (targetPanel) {
                    targetPanel.classList.add('active');
                }

                // 根据标签页加载相应图表
                setTimeout(() => {
                    this.loadTabChart(targetTab);
                }, 100);
            });
        });
    },

    // 根据标签页加载图表
    loadTabChart: function(tabName) {
        switch (tabName) {
            case 'features':
                this.initFeatureImportanceChart();
                break;
            case 'predictions':
                this.initPredictionAccuracyChart();
                break;
        }
    },

    // 初始化所有图表
    initCharts: function() {
        this.initMetricsComparisonChart();
        this.initTrainingTimeChart();
        this.initPerformanceRadarChart();
    },

    // 确保容器可见性和尺寸
    ensureContainerReady: function(containerId) {
        const container = document.getElementById(containerId);
        if (!container) return false;
        
        // 强制显示容器
        container.style.display = 'block';
        container.style.visibility = 'visible';
        
        // 检查容器尺寸
        const rect = container.getBoundingClientRect();
        if (rect.width === 0 || rect.height === 0) {
            // 强制设置最小尺寸
            container.style.minHeight = '300px';
            container.style.minWidth = '100%';
            // 强制重新计算布局
            container.offsetHeight;
        }
        
        return true;
    },

    // 性能指标对比图表
    initMetricsComparisonChart: function() {
        const chartDom = document.getElementById('metricsComparisonChart');
        if (!chartDom || !this.ensureContainerReady('metricsComparisonChart')) return;

        // 销毁已存在的图表实例
        if (this.chartInstances.metricsComparison) {
            this.chartInstances.metricsComparison.dispose();
        }

        const chart = echarts.init(chartDom);
        this.chartInstances.metricsComparison = chart;
        
        const option = {
            title: {
                text: '模型性能指标对比',
                left: 'center',
                textStyle: {
                    fontSize: 16,
                    fontWeight: 'normal'
                }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            legend: {
                data: ['R² 决定系数', 'RMSE (×10)'],
                top: 30
            },
            xAxis: {
                type: 'category',
                data: ['随机森林', 'XGBoost', 'LSTM'],
                axisLabel: {
                    fontSize: 12
                }
            },
            yAxis: {
                type: 'value',
                name: '数值',
                min: 0,
                max: 1.0,
                axisLabel: {
                    formatter: '{value}'
                }
            },
            series: [
                {
                    name: 'R² 决定系数',
                    type: 'bar',
                    data: [0.991896, 0.990004, 0.994590],
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: '#83bff6' },
                            { offset: 1, color: '#188df0' }
                        ])
                    }
                },
                {
                    name: 'RMSE (×10)',
                    type: 'bar',
                    data: [0.80438, 0.89337, 0.65784],
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: '#ffeaa7' },
                            { offset: 1, color: '#fab1a0' }
                        ])
                    }
                }
            ]
        };

        chart.setOption(option);
        
        // 响应式调整
        window.addEventListener('resize', () => {
            chart.resize();
        });
    },

    // 训练时间对比图表
    initTrainingTimeChart: function() {
        const chartDom = document.getElementById('trainingTimeChart');
        if (!chartDom || !this.ensureContainerReady('trainingTimeChart')) return;

        // 销毁已存在的图表实例
        if (this.chartInstances.trainingTime) {
            this.chartInstances.trainingTime.dispose();
        }

        const chart = echarts.init(chartDom);
        this.chartInstances.trainingTime = chart;
        
        const option = {
            title: {
                text: '模型训练时间对比',
                left: 'center',
                textStyle: {
                    fontSize: 16,
                    fontWeight: 'normal'
                }
            },
            tooltip: {
                trigger: 'axis',
                formatter: function(params) {
                    const value = params[0].value;
                    return `${params[0].name}<br/>训练时间: ${value.toFixed(2)} 秒`;
                }
            },
            xAxis: {
                type: 'category',
                data: ['随机森林', 'XGBoost', 'LSTM'],
                axisLabel: {
                    fontSize: 12
                }
            },
            yAxis: {
                type: 'value',
                name: '时间 (秒)',
                axisLabel: {
                    formatter: '{value}s'
                }
            },
            series: [
                {
                    type: 'bar',
                    data: [0.898, 1.408, 148.138],
                    itemStyle: {
                        color: function(params) {
                            const colors = ['#22c55e', '#3b82f6', '#8b5cf6'];
                            return colors[params.dataIndex];
                        }
                    },
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}s'
                    }
                }
            ]
        };

        chart.setOption(option);
        
        window.addEventListener('resize', () => {
            chart.resize();
        });
    },

    // 性能雷达图
    initPerformanceRadarChart: function() {
        const chartDom = document.getElementById('performanceRadarChart');
        if (!chartDom || !this.ensureContainerReady('performanceRadarChart')) return;

        // 销毁已存在的图表实例
        if (this.chartInstances.performanceRadar) {
            this.chartInstances.performanceRadar.dispose();
        }

        const chart = echarts.init(chartDom);
        this.chartInstances.performanceRadar = chart;
        
        // 数据标准化处理
        const maxValues = {
            r2: 1.0,
            speed: 150, // 最大训练时间
            accuracy: 1.0,
            efficiency: 1.0
        };

        const option = {
            title: {
                text: '模型综合性能雷达图',
                left: 'center',
                textStyle: {
                    fontSize: 16,
                    fontWeight: 'normal'
                }
            },
            tooltip: {
                trigger: 'item'
            },
            legend: {
                data: ['随机森林', 'XGBoost', 'LSTM'],
                top: 30
            },
            radar: {
                indicator: [
                    { name: '准确性 (R²)', max: 1.0 },
                    { name: '训练速度', max: 1.0 },
                    { name: '误差控制', max: 1.0 },
                    { name: '模型效率', max: 1.0 },
                    { name: '实用性', max: 1.0 }
                ],
                center: ['50%', '60%'],
                radius: 120
            },
            series: [
                {
                    name: '模型性能',
                    type: 'radar',
                    data: [
                        {
                            value: [0.991896, 0.95, 0.85, 0.90, 0.92],
                            name: '随机森林',
                            areaStyle: {
                                opacity: 0.1,
                                color: '#22c55e'
                            },
                            itemStyle: {
                                color: '#22c55e'
                            }
                        },
                        {
                            value: [0.990004, 0.92, 0.82, 0.88, 0.89],
                            name: 'XGBoost',
                            areaStyle: {
                                opacity: 0.1,
                                color: '#3b82f6'
                            },
                            itemStyle: {
                                color: '#3b82f6'
                            }
                        },
                        {
                            value: [0.994590, 0.20, 0.95, 0.75, 0.85],
                            name: 'LSTM',
                            areaStyle: {
                                opacity: 0.1,
                                color: '#8b5cf6'
                            },
                            itemStyle: {
                                color: '#8b5cf6'
                            }
                        }
                    ]
                }
            ]
        };

        chart.setOption(option);
        
        window.addEventListener('resize', () => {
            chart.resize();
        });
    },

    // 特征重要性图表
    initFeatureImportanceChart: function() {
        const chartDom = document.getElementById('featureImportanceChart');
        if (!chartDom || !this.ensureContainerReady('featureImportanceChart')) return;

        // 销毁已存在的图表实例
        if (this.chartInstances.featureImportance) {
            this.chartInstances.featureImportance.dispose();
        }

        const chart = echarts.init(chartDom);
        this.chartInstances.featureImportance = chart;
        
        const option = {
            title: {
                text: '传感器特征重要性分析',
                left: 'center',
                textStyle: {
                    fontSize: 16,
                    fontWeight: 'normal'
                }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            xAxis: {
                type: 'value',
                name: '重要性得分'
            },
            yAxis: {
                type: 'category',
                data: ['CO2浓度', 'PIR运动', '温度传感器', '光照传感器', '声音传感器'],
                axisLabel: {
                    fontSize: 12
                }
            },
            series: [
                {
                    type: 'bar',
                    data: [0.32, 0.28, 0.18, 0.14, 0.08],
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                            { offset: 0, color: '#83bff6' },
                            { offset: 1, color: '#188df0' }
                        ])
                    },
                    label: {
                        show: true,
                        position: 'right',
                        formatter: '{c}'
                    }
                }
            ]
        };

        chart.setOption(option);
        
        window.addEventListener('resize', () => {
            chart.resize();
        });
    },

    // 预测准确性图表
    initPredictionAccuracyChart: function() {
        const chartDom = document.getElementById('predictionAccuracyChart');
        if (!chartDom || !this.ensureContainerReady('predictionAccuracyChart')) return;

        // 销毁已存在的图表实例
        if (this.chartInstances.predictionAccuracy) {
            this.chartInstances.predictionAccuracy.dispose();
        }

        const chart = echarts.init(chartDom);
        this.chartInstances.predictionAccuracy = chart;
        
        // 模拟预测vs实际数据
        const actualData = [];
        const rfPredData = [];
        const xgbPredData = [];
        const lstmPredData = [];
        
        for (let i = 0; i < 50; i++) {
            const actual = Math.random() * 3 + 0.5;
            actualData.push(actual);
            rfPredData.push(actual + (Math.random() - 0.5) * 0.2);
            xgbPredData.push(actual + (Math.random() - 0.5) * 0.25);
            lstmPredData.push(actual + (Math.random() - 0.5) * 0.15);
        }
        
        const option = {
            title: {
                text: '模型预测准确性对比',
                left: 'center',
                textStyle: {
                    fontSize: 16,
                    fontWeight: 'normal'
                }
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['实际值', '随机森林', 'XGBoost', 'LSTM'],
                top: 30
            },
            xAxis: {
                type: 'category',
                data: Array.from({length: 50}, (_, i) => i + 1),
                name: '样本序号'
            },
            yAxis: {
                type: 'value',
                name: '房间占用人数'
            },
            series: [
                {
                    name: '实际值',
                    type: 'line',
                    data: actualData,
                    symbol: 'circle',
                    symbolSize: 4,
                    lineStyle: {
                        color: '#1f2937',
                        width: 2
                    }
                },
                {
                    name: '随机森林',
                    type: 'line',
                    data: rfPredData,
                    symbol: 'circle',
                    symbolSize: 3,
                    lineStyle: {
                        color: '#22c55e',
                        width: 1.5
                    }
                },
                {
                    name: 'XGBoost',
                    type: 'line',
                    data: xgbPredData,
                    symbol: 'circle',
                    symbolSize: 3,
                    lineStyle: {
                        color: '#3b82f6',
                        width: 1.5
                    }
                },
                {
                    name: 'LSTM',
                    type: 'line',
                    data: lstmPredData,
                    symbol: 'circle',
                    symbolSize: 3,
                    lineStyle: {
                        color: '#8b5cf6',
                        width: 1.5
                    }
                }
            ]
        };

        chart.setOption(option);
        
        window.addEventListener('resize', () => {
            chart.resize();
        });
    },

    // 设置刷新按钮
    setupRefreshButton: function() {
        const refreshBtn = document.getElementById('refresh-models');
        if (!refreshBtn) return;

        refreshBtn.addEventListener('click', () => {
            const icon = document.getElementById('refresh-models-icon');
            icon.classList.add('fa-spin');
            
            // 模拟数据刷新
            setTimeout(() => {
                icon.classList.remove('fa-spin');
                this.initCharts();
                console.log('模型数据已刷新');
            }, 1000);
        });
    },

    // 调整所有图表尺寸
    resizeCharts: function() {
        Object.values(this.chartInstances).forEach(chart => {
            if (chart && chart.resize) {
                chart.resize();
            }
        });
    },

    // 强制重新初始化所有图表
    reinitCharts: function() {
        console.log('重新初始化模型性能图表...');
        
        // 等待一帧，确保DOM更新
        requestAnimationFrame(() => {
            this.initCharts();
            
            // 再次调整尺寸
            setTimeout(() => {
                this.resizeCharts();
            }, 100);
        });
    },

    // 销毁所有图表
    dispose: function() {
        // 清理图表实例
        Object.values(this.chartInstances).forEach(chart => {
            if (chart && chart.dispose) {
                chart.dispose();
            }
        });
        this.chartInstances = {};
        this.isInitialized = false;
    }
};

// 导出到全局
window.ModelsPerformance = ModelsPerformance; 